import { config } from './modules/config';
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var DailyFile = require('./modules/common/dailyfile');
var dynamicRoute = require('./modules/common/dynamic-routes');

export function getApp(app) {
    app.use(logger('common', {
        stream: DailyFile.getStream({
            filename: path.normalize(path.join(config.logRootDir, 'access-%DATE%.log')),
            date_format: 'YYYYMMDDHH',
            frequency: '1h',
            verbose: false
        })
    }));
    if (process.env.NODE_ENV != 'test') app.use(logger('dev'));
    app.use(bodyParser.json({ limit: '10mb' }));
    app.use(bodyParser.urlencoded({ limit: '10mb', extended: false }));
    app.use(cookieParser());

    dynamicRoute.loads(app, __dirname + '/routes', '../../routes/');

    // catch 404 and forward to error handler
    app.use(function (req, res, next) {
        var err = new Error('Not Found');
        (<any>err).status = 404;
        next(err);
    });

    // error handlers

    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
        app.use(function (err, req, res, next) {
            res.status(err.status || 500);
            res.json({
                message: err.message,
                error: err
            });
        });
    }

    // production error handler
    // no stacktraces leaked to user
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.json('error', {
            message: err.message,
            error: {}
        });
    });
    return app;
}